//
//  TwoMovieTableViewController.m
//  开心一刻
//
//  Created by lanou on 16/4/7.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "TwoMovieTableViewController.h"
#import "Requestmanager.h"
#import "HZWMovieModel.h"
#import "HZWMovieTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "HZWPlayView.h"
#import "HZWMovieWebViewController.h"
#import "PlayViewController.h"
#import "AppDelegate.h"
#import "MJRefresh.h"


@interface TwoMovieTableViewController ()
@property(nonatomic,strong)NSMutableArray* modelArrayy;
@property (nonatomic,strong)Requestmanager * manageq;
@property(nonatomic,strong)HZWPlayView * player;
@property(nonatomic,strong)HZWMovieTableViewCell * Moviecell;
@property(nonatomic,strong)NSIndexPath * index;
@property(nonatomic,strong)NSTimer * timer;
@property(nonatomic,strong)UIButton * changeButton;
@property(nonatomic,strong)NSString * string;
@property(nonatomic,assign)NSInteger time;
@property(nonatomic,assign)NSInteger aa;
@end

@implementation TwoMovieTableViewController
// 下拉刷新
-(void)requestFresh
{
    self.aa++;
    NSString * string = @"http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-104&iid=3598776185&os_version=9.0.2&os_api=18&app_name=joke_essay&channel=App%20Store&device_platform=iphone&idfa=073F20C4-A8E1-4FF1-A108-FD2C3D1E2A2A&vid=CEE298FE-2CE3-4B46-9B8F-300B8C1C513C&openudid=ae1e4625636f7cf8f2a3ce5fbacb1606881639ee&device_type=iPhone%206&version_code=5.0.1&ac=WIFI&screen_width=750&device_id=7084213935&aid=7&city=%E4%B8%8A%E6%B5%B7%E5%B8%82&content_type=-104&count=30&essence=1&latitude=31.13008042868888&longitude=121.2840079459284&message_cursor=0&min_time=";
    NSString * str = [NSString stringWithFormat:@"%ld&mpic=1",_aa];
    // 将改变的字符串拼接到新的url后面
    NSString * str1 = [string stringByAppendingString:str];
    [Requestmanager requestWithUrl:str1 requesType:requestTypeGET parDic:nil finish:^(NSData *data) {
        NSDictionary * dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.modelArrayy = [HZWMovieModel requestMovie:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        [self.tableView .mj_header endRefreshing];
    } error:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}
// 上拉加载
-(void)requestMore
{
    self.aa--;
    NSString * string = @"http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-104&iid=3598776185&os_version=9.0.2&os_api=18&app_name=joke_essay&channel=App%20Store&device_platform=iphone&idfa=073F20C4-A8E1-4FF1-A108-FD2C3D1E2A2A&vid=CEE298FE-2CE3-4B46-9B8F-300B8C1C513C&openudid=ae1e4625636f7cf8f2a3ce5fbacb1606881639ee&device_type=iPhone%206&version_code=5.0.1&ac=WIFI&screen_width=750&device_id=7084213935&aid=7&city=%E4%B8%8A%E6%B5%B7%E5%B8%82&content_type=-104&count=30&essence=1&latitude=31.13008042868888&longitude=121.2840079459284&message_cursor=0&min_time=";
    NSString * str = [NSString stringWithFormat:@"%ld&mpic=1",_aa];
    NSString * str1  = [string stringByAppendingString:str];
    [Requestmanager requestWithUrl:str1 requesType:requestTypeGET parDic:nil finish:^(NSData *data) {
        NSDictionary * dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * array = [HZWMovieModel requestMovie:dic];
        for (HZWMovieModel * model in array) {
            [self.modelArrayy addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        [self.tableView.mj_footer endRefreshing];
    } error:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}
// 网络请求数据
-(void)request
{
    
    [Requestmanager requestWithUrl:@"http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-104&iid=3598776185&os_version=9.0.2&os_api=18&app_name=joke_essay&channel=App%20Store&device_platform=iphone&idfa=073F20C4-A8E1-4FF1-A108-FD2C3D1E2A2A&vid=CEE298FE-2CE3-4B46-9B8F-300B8C1C513C&openudid=ae1e4625636f7cf8f2a3ce5fbacb1606881639ee&device_type=iPhone%206&version_code=5.0.1&ac=WIFI&screen_width=750&device_id=7084213935&aid=7&city=%E4%B8%8A%E6%B5%B7%E5%B8%82&content_type=-104&count=30&essence=1&latitude=31.13008042868888&longitude=121.2840079459284&message_cursor=0&min_time=1460018702&mpic=1"
        requesType:requestTypeGET parDic:nil finish:^(NSData *data1)
    {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
       // NSLog(@"%@",dic);
     
        self.modelArrayy = [HZWMovieModel requestMovie:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } error:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self request];
    self.aa =1460018702;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestFresh];
    }];
     self.tableView.mj_footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
         [self requestMore];
     }];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _modelArrayy.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    HZWMovieModel* model = _modelArrayy[indexPath.row];
    
    static NSString * cellindentify = @"movie";
    HZWMovieTableViewCell * cell =[tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[HZWMovieTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellindentify];
    }

    cell.betterText.text =model.BetterText;
    cell.contentLabel.text = model.content;
    [cell.aotuImage sd_setImageWithURL:[NSURL URLWithString:model.avatar_url] completed:nil];
    cell.username.text = model.user_name;
    cell.aotunameLabel.text = model.name;
    [cell.contentImage sd_setImageWithURL:[NSURL URLWithString:model.url] completed:nil];
    cell.style.text = model.category_name;
    [cell.betterImage sd_setImageWithURL:[NSURL URLWithString:model.betterImage]placeholderImage:[UIImage imageNamed:@"521.png"]];
    cell.playTimelabel.text = [NSString stringWithFormat:@"%ld次播放",model.play_count];
    cell.allTime.text = [NSString stringWithFormat:@"%02ld:%02ld",model.duration/60,model.duration%60];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell titleHight:model];
    cell.palyButton.tag = indexPath.row+100;
    [cell.palyButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.jubaoButton addTarget:self action:@selector(jubaoAction:) forControlEvents:UIControlEventTouchUpInside];
   
    
    return cell;
}
-(void)jubaoAction:(UIButton *)button
{
   
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:@"输入您举报的内容" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"举报提交成功 稍后会进行核实 谢谢" preferredStyle:UIAlertControllerStyleAlert];
        
        [aler addAction:[UIAlertAction  actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        [self presentViewController:aler animated:NO completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    }];
    [self presentViewController:alert animated:NO completion:nil];
    
  
}

-(void)buttonAction:(UIButton *)button

{
    [self.player.player pause];
    _Moviecell = (HZWMovieTableViewCell *)button.superview.superview.superview;
    _index = [self.tableView indexPathForCell:_Moviecell];
    HZWMovieModel *model = _modelArrayy[button.tag-100];
        UIView * view1 = button.superview;
    
    _player = [[HZWPlayView alloc]initWithFrame:CGRectMake(0, 0, view1.frame.size.width, view1.frame.size.height) url:model.mp4_url];
    self.string = model.mp4_url;
    [view1 addSubview:_player];
    self.time =(int)_player.player.currentTime.value /_player.player.currentTime.timescale;
    
    self.changeButton =[UIButton buttonWithType:UIButtonTypeCustom];
    self.changeButton.frame = CGRectMake(view1.frame.size.width-30, view1.frame.size.height-20, 30, 20);
    //self.changeButton.backgroundColor =[UIColor redColor];
    [self.changeButton addTarget:self action:@selector(changAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.changeButton setTitle:@"全屏" forState:UIControlStateNormal];
    self.changeButton .font = [UIFont systemFontOfSize:13];
    [self.player addSubview:_changeButton];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timer :) userInfo:nil repeats:YES];
    NSLog(@"121");
    
}

-(void)changAction:(UIButton *)button
{
    PlayViewController * pl =[[PlayViewController alloc]init];
    pl.string = _string;
    pl.currTIme = _time;
    AppDelegate * app =[UIApplication sharedApplication].delegate;
    app.isOk = YES;
    [self presentViewController:pl animated:NO completion:nil];
    
    
}
- (void)timer: (NSTimer *)timer
{
    CGRect cellR = [self.tableView rectForRowAtIndexPath:_index];
    if (self.tableView.contentOffset.y -cellR.origin.y <_Moviecell.frame.size.height ||cellR.origin.y - self.tableView.contentOffset.y >self.tableView.frame.size.height)
    {
        
    }
    else
    {
        [_player.player pause];
        
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HZWMovieModel * model= _modelArrayy[indexPath.row];
    if (model.content== nil)
    {
        return 0;
    }
    else
    {
        return  [HZWMovieTableViewCell cellHight:model];
    }
    
   
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HZWMovieWebViewController * webview = [[HZWMovieWebViewController alloc]init];
    HZWMovieModel * model = _modelArrayy[indexPath.row];
    webview.webviewstring = model.share_url;
    [self.navc pushViewController:webview animated:YES];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
